package com.lagou.controller;

import com.lagou.service.CodeServiceFeignClient;
import com.lagou.service.ILagouAuthCodeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/code")
//@CrossOrigin()
@Slf4j
public class CodeController {
    @Autowired
    private CodeServiceFeignClient codeServiceFeignClient;

    @Autowired
    @Qualifier("lagouAuthCodeServiceImpl")
    private ILagouAuthCodeService ilagouAuthCodeService;

    public static final int AVALIABLE_PROCESSORS = Runtime.getRuntime().availableProcessors();
    public static ThreadPoolExecutor executor = new ThreadPoolExecutor(AVALIABLE_PROCESSORS, AVALIABLE_PROCESSORS, 1, TimeUnit.MINUTES,
            new LinkedBlockingQueue<>(5), new ThreadPoolExecutor.CallerRunsPolicy());

    @RequestMapping("/create/{email}")
    public boolean create(@PathVariable("email") String email) {
        StringBuffer stringBuffer = new StringBuffer();
        Random random = new Random();
        for (int k = 0; k < 6; k++) {
            stringBuffer.append(random.nextInt(10));
        }
        String code = stringBuffer.toString();
        log.info("create code:{}", code);
        // ⽣成验证码并发送到对应邮箱，成功true，失败false




        CompletableFuture completableFuture = new CompletableFuture();
//        executor.execute(() -> {
//            log.info("begin to request>>");
//            String result="";
//            try {
//                result = codeServiceFeignClient.sendEmail(email, code);
//            } catch (Exception e) {
//
//            }
//            completableFuture.complete(result);
//        });
        CompletableFuture cf = CompletableFuture.supplyAsync(() -> {
            return  codeServiceFeignClient.sendEmail(email, code);
        }, executor);
//        cf.get()

//        FutureTask<String> ft1 = new FutureTask<String>(ca1);
        try {
            // 阻塞获得结果

            Object object = cf.get();
            log.info("aaa===");
            String result = object == null ? "" : object.toString();
            if (StringUtils.isNotEmpty(result) && "true".equals(result)) {

                // 写入
                ilagouAuthCodeService.addUserCode(code, email);

                return true;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        log.info("create execute success");
        return false;
    }

    @RequestMapping("/validate/{email}/{code}")
    public String validateCode(@PathVariable("email")String email,@PathVariable("code")String code) {
        // 校验验证码是否正确，0正确1错误2超时

        return ilagouAuthCodeService.validateCode(email,code)+"";
    }

}
